const { getRecordByUserId, getUserInfoByUserId, getPeerByUserId, getRanksByUserId, getHeroesByUserId, getTotalByUserId, getWordcloudByUserId } = require('../dota2api/index')
const dota2helper = require('./dota2helper')
const { hasMonitorGame } = require('../api/gameList')
const { getPlayerHistory } = require('../stratzApi/index')
const { getReport } = require('../reportManager')
const { getHeroCnName, getItemCnName } = require('./dota2helper')

const noGameMessageList = [
  '今天一场也没打,真tm不酬勤',
  '就像一条懒狗,今天没打过刀塔',
  '想做个云玩家,指点群友',
  '可能被演怕了,今天还没打过任何比赛',
  '还不快上线,都没打过查你ma的战绩呢',
  '偶像不打你也不打了?今天未查询到任何记录!',
  '还在see?今天一场也没打!',
  '对不起未查到,今天有打过游戏!',
  '是关了战绩吗?没查到任何信息',
  '打没打心里没b数还在这里查?一场都没有!',
  '你今天好像还没有打过游戏哦'
]

// 获取战绩
function getRecord(userId = 215510959) {
  return new Promise((resolve, reject) => {
    getRecordByUserId(userId).then(async res => {
      const userInfo = await getUserInfoByUserId(userId)
      const tierLevel = await dota2helper.getRankTier(userInfo.rank_tier, userInfo.leaderboard_rank)
      if (!userInfo.profile) {
        resolve(`没有找到该玩家信息,请输入正确的数字ID`)
      }
      if (res.length === 0) {
        resolve(`\n【${userInfo.profile.personaname}】${tierLevel}${noGameMessageList[Number((Math.random() * (noGameMessageList.length - 1)).toFixed(0))]}`)
      } else {
        let total = 0 // 游戏总数
        let win = 0 // 赢总数
        let lose = 0 // 输总数
        let ladderTotal = 0 // 天梯总数
        let ladderSingleTotal = 0 // 天梯单排总数
        let ladderPartyTotal = 0 // 天梯组排总数
        let ladderSingleWin = 0 // 天梯单排赢
        let ladderSingleLose = 0 // 天梯单排输
        let ladderPartyWin = 0 // 天梯组排赢
        let ladderPartLose = 0 // 天梯组排输
        let ladderToday = 0 // 天梯分

        let highestKills = 0 // 最高杀人
        let highestKillsHero = '未知'
        let highestDeaths = 0 // 最高死亡
        let highestDeathsHero = '未知'
        let highestAssists = 0 // 最高助攻
        let highestAssistsHero = '未知'
        let highestHeroDamage = 0 // 最高伤害
        let highestHeroDamageHero = '未知'
        let highestHeroHealing = 0 // 最高治疗
        let highestHeroHealingHero = '未知'
        let highestXpm = 0 // 最高XPM
        let highestXpmHero = '未知'
        let highestGpm = 0 // 最高GPM
        let highestGpmHero = '未知'
        let today = new Date(`${new Date().toLocaleDateString()} 00:00:00`).getTime()
        res.forEach(item => {
          if (item.start_time * 1000 > today) {
            total++
            if (dota2helper.isWin(item.player_slot, item.radiant_win)) {
              win++
            } else {
              lose++
            }
            if (dota2helper.isLadder(item.lobby_type)) { // 天梯
              ladderTotal++
              if (dota2helper.isParty(item.party_size)) { // 组排
                ladderPartyTotal++
                if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                  ladderPartyWin++
                  ladderToday += 20
                } else { // 输
                  ladderPartLose++
                  ladderToday -= 20
                }
              } else { // 单排
                ladderSingleTotal++
                if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                  ladderSingleWin++
                  ladderToday += 30
                } else { // 输
                  ladderSingleLose++
                  ladderToday -= 30
                }
              }
            }
            if (item.kills > highestKills) {
              highestKills = item.kills
              highestKillsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.deaths > highestDeaths) {
              highestDeaths = item.deaths
              highestDeathsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.assists > highestAssists) {
              highestAssists = item.assists
              highestAssistsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.hero_damage > highestHeroDamage) {
              highestHeroDamage = item.hero_damage
              highestHeroDamageHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.hero_healing > highestHeroHealing) {
              highestHeroHealing = item.hero_healing
              highestHeroHealingHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.xp_per_min > highestXpm) {
              highestXpm = item.xp_per_min
              highestXpmHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.gold_per_min > highestGpm) {
              highestGpm = item.gold_per_min
              highestGpmHero = dota2helper.getHeroCnName(item.hero_id)
            }
          }
        })
        if (total === 0) {
          resolve(`\n【${userInfo.profile.personaname}】${tierLevel}${noGameMessageList[Number((Math.random() * noGameMessageList.length).toFixed(0))]}`)
        } else {

          let message = `\n【${userInfo.profile.personaname}】${tierLevel}
====所有比赛====
总局数【${total}】赢【${win}】输【${lose}】胜率【${toPercent(win / total)}】

====天梯比赛====
总数【${ladderTotal}】赢【${ladderSingleWin + ladderPartyWin}】输【${ladderSingleLose + ladderPartLose}】胜率【${toPercent((ladderSingleWin + ladderPartyWin) / ladderTotal)}】

----单排----
赢【${ladderSingleWin}】输【${ladderSingleLose}】胜率【${toPercent(ladderSingleWin / ladderSingleTotal)}】

----组排----
赢【${ladderPartyWin}】输【${ladderPartLose}】胜率【${toPercent(ladderPartyWin / ladderPartyTotal)}】

----天梯分----
【${ladderToday > 0 ? '+' + ladderToday : ladderToday}】

====最高记录====
击杀【${highestKills}】 英雄【${highestKillsHero}】

死亡【${highestDeaths}】 英雄【${highestDeathsHero}】

助攻【${highestAssists}】 英雄【${highestAssistsHero}】

伤害【${highestHeroDamage}】 英雄【${highestHeroDamageHero}】

治疗【${highestHeroHealing}】 英雄【${highestHeroHealingHero}】

每分钟获得经验【${highestXpm}】 英雄【${highestXpmHero}】

每分钟获得金钱【${highestGpm}】 英雄【${highestGpmHero}】
`
          resolve(message)
        }
      }
    }).catch(e => {
      reject(e)
    })
  })
}

// 周报
function getLastWeekRecord(userId = 215510959) {
  return new Promise((resolve, reject) => {
    getRecordByUserId(userId).then(async res => {
      const userInfo = await getUserInfoByUserId(userId)
      const tierLevel = await dota2helper.getRankTier(userInfo.rank_tier, userInfo.leaderboard_rank)
      if (!userInfo.profile) {
        resolve(`没有找到该玩家信息,请输入正确的数字ID`)
      }
      if (res.length === 0) {
        resolve(`\n【${userInfo.profile.personaname}】${tierLevel}${noGameMessageList[Number((Math.random() * noGameMessageList.length).toFixed(0))]}`)
      } else {
        let total = 0 // 游戏总数
        let win = 0 // 赢总数
        let lose = 0 // 输总数
        let ladderTotal = 0 // 天梯总数
        let ladderSingleTotal = 0 // 天梯单排总数
        let ladderPartyTotal = 0 // 天梯组排总数
        let ladderSingleWin = 0 // 天梯单排赢
        let ladderSingleLose = 0 // 天梯单排输
        let ladderPartyWin = 0 // 天梯组排赢
        let ladderPartLose = 0 // 天梯组排输
        let ladderToday = 0 // 天梯分

        let highestKills = 0 // 最高杀人
        let highestKillsHero = '未知'
        let highestDeaths = 0 // 最高死亡
        let highestDeathsHero = '未知'
        let highestAssists = 0 // 最高助攻
        let highestAssistsHero = '未知'
        let highestHeroDamage = 0 // 最高伤害
        let highestHeroDamageHero = '未知'
        let highestHeroHealing = 0 // 最高治疗
        let highestHeroHealingHero = '未知'
        let highestXpm = 0 // 最高XPM
        let highestXpmHero = '未知'
        let highestGpm = 0 // 最高GPM
        let highestGpmHero = '未知'
        // let today = new Date(`${new Date().toLocaleDateString()} 00:00:00`).getTime()
        const d1 = new Date(), d2 = new Date();
        let t1, t2 = 0;
        t1 = new Date(d1.setDate(d1.getDate() - 6 - d1.getDay())).setHours(0, 0, 0, 999);
        t2 = new Date(d2.setDate(d2.getDate() - d2.getDay())).setHours(23, 59, 59, 999);
        res.forEach(item => {
          if (item.start_time * 1000 > t1 && item.start_time * 1000 < t2) {
            total++
            if (dota2helper.isWin(item.player_slot, item.radiant_win)) {
              win++
            } else {
              lose++
            }
            if (dota2helper.isLadder(item.lobby_type)) { // 天梯
              ladderTotal++
              if (dota2helper.isParty(item.party_size)) { // 组排
                ladderPartyTotal++
                if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                  ladderPartyWin++
                  ladderToday += 20
                } else { // 输
                  ladderPartLose++
                  ladderToday -= 20
                }
              } else { // 单排
                ladderSingleTotal++
                if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                  ladderSingleWin++
                  ladderToday += 30
                } else { // 输
                  ladderSingleLose++
                  ladderToday -= 30
                }
              }
            }
            if (item.kills > highestKills) {
              highestKills = item.kills
              highestKillsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.deaths > highestDeaths) {
              highestDeaths = item.deaths
              highestDeathsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.assists > highestAssists) {
              highestAssists = item.assists
              highestAssistsHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.hero_damage > highestHeroDamage) {
              highestHeroDamage = item.hero_damage
              highestHeroDamageHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.hero_healing > highestHeroHealing) {
              highestHeroHealing = item.hero_healing
              highestHeroHealingHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.xp_per_min > highestXpm) {
              highestXpm = item.xp_per_min
              highestXpmHero = dota2helper.getHeroCnName(item.hero_id)
            }
            if (item.gold_per_min > highestGpm) {
              highestGpm = item.gold_per_min
              highestGpmHero = dota2helper.getHeroCnName(item.hero_id)
            }
          }
        })
        if (total === 0) {
          resolve(`\n【${userInfo.profile.personaname}】${tierLevel}${noGameMessageList[Number((Math.random() * noGameMessageList.length).toFixed(0))]}`)
        } else {

          let message = `\n【${userInfo.profile.personaname}】${tierLevel}
====所有比赛====
总局数【${total}】赢【${win}】输【${lose}】胜率【${toPercent(win / total)}】

====天梯比赛====
总数【${ladderTotal}】赢【${ladderSingleWin + ladderPartyWin}】输【${ladderSingleLose + ladderPartLose}】胜率【${toPercent((ladderSingleWin + ladderPartyWin) / ladderTotal)}】

----单排----
赢【${ladderSingleWin}】输【${ladderSingleLose}】胜率【${toPercent(ladderSingleWin / ladderSingleTotal)}】

----组排----
赢【${ladderPartyWin}】输【${ladderPartLose}】胜率【${toPercent(ladderPartyWin / ladderPartyTotal)}】

----天梯分----
【${ladderToday > 0 ? '+' + ladderToday : ladderToday}】

====最高记录====
击杀【${highestKills}】 英雄【${highestKillsHero}】

死亡【${highestDeaths}】 英雄【${highestDeathsHero}】

助攻【${highestAssists}】 英雄【${highestAssistsHero}】

伤害【${highestHeroDamage}】 英雄【${highestHeroDamageHero}】

治疗【${highestHeroHealing}】 英雄【${highestHeroHealingHero}】

每分钟获得经验【${highestXpm}】 英雄【${highestXpmHero}】

每分钟获得金钱【${highestGpm}】 英雄【${highestGpmHero}】
`
          resolve(message)
        }
      }
    }).catch(e => {
      reject(e)
    })
  })
}

// 年报
function getThisYearRecord(userId = 215510959) {
  return new Promise((resolve, reject) => {
    getRecordByUserId(userId, 360).then(async res => {
      const thisYearStartTime = new Date('2020-01-01').getTime()
      const thisYearEndTime = new Date('2020-12-31').getTime()
      const matchList = res.filter(item =>{
        return item.start_time * 1000 > thisYearStartTime && item.start_time < thisYearEndTime
      })
      const userInfo = await getUserInfoByUserId(userId)
      const tierLevel = await dota2helper.getRankTier(userInfo.rank_tier, userInfo.leaderboard_rank)
      if (!userInfo.profile) {
        resolve(`没有找到该玩家信息,请输入正确的数字ID`)
      }
      if (matchList.length === 0) {
        resolve(`\n【${userInfo.profile.personaname}】${tierLevel}${noGameMessageList[Number((Math.random() * noGameMessageList.length).toFixed(0))]}`)
      } else {
        let total = matchList.length // 游戏总数
        let totalDuration = 0 // 总游戏时长
        let win = 0 // 赢总数
        let lose = 0 // 输总数
        let ladderTotal = 0 // 天梯总数
        let ladderSingleTotal = 0 // 天梯单排总数
        let ladderPartyTotal = 0 // 天梯组排总数
        let ladderSingleWin = 0 // 天梯单排赢
        let ladderSingleLose = 0 // 天梯单排输
        let ladderPartyWin = 0 // 天梯组排赢
        let ladderPartLose = 0 // 天梯组排输
        let ladderToday = 0 // 天梯分

        let highestKills = 0 // 最高杀人
        let highestKillsHero = '未知'
        let highestDeaths = 0 // 最高死亡
        let highestDeathsHero = '未知'
        let highestAssists = 0 // 最高助攻
        let highestAssistsHero = '未知'
        let highestDurationGame = 0 // 最长游戏时长
        let minimunDurationGame = 0 // 最短游戏时长

        let totalKills = 0 // 总杀敌
        let totalAssists = 0 // 总助攻
        let totalDeaths = 0 // 总死亡

        let heroList = [] // 英雄使用情况

        matchList.forEach(item => {
          totalDuration += item.duration
          totalKills += item.kills
          totalAssists += item.assists
          totalDeaths += item.deaths
          if (dota2helper.isWin(item.player_slot, item.radiant_win)) {
            win++
          } else {
            lose++
          }
          if (dota2helper.isLadder(item.lobby_type)) { // 天梯
            ladderTotal++
            if (dota2helper.isParty(item.party_size)) { // 组排
              ladderPartyTotal++
              if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                ladderPartyWin++
                ladderToday += 20
              } else { // 输
                ladderPartLose++
                ladderToday -= 20
              }
            } else { // 单排
              ladderSingleTotal++
              if (dota2helper.isWin(item.player_slot, item.radiant_win)) { // 赢
                ladderSingleWin++
                ladderToday += 30
              } else { // 输
                ladderSingleLose++
                ladderToday -= 30
              }
            }
          }
          if (item.kills > highestKills) {
            highestKills = item.kills
            highestKillsHero = dota2helper.getHeroCnName(item.hero_id)
          }
          if (item.deaths > highestDeaths) {
            highestDeaths = item.deaths
            highestDeathsHero = dota2helper.getHeroCnName(item.hero_id)
          }
          if (item.assists > highestAssists) {
            highestAssists = item.assists
            highestAssistsHero = dota2helper.getHeroCnName(item.hero_id)
          }
          if (item.duration > highestDurationGame) {
            highestDurationGame = item.duration
          }
          if (item.duration < minimunDurationGame) {
            minimunDurationGame = item.duration
          }

          if (heroList.find(hero => { return hero.id === item.hero_id })) {
            let index = heroList.findIndex(hero => { return hero.id === item.hero_id })
            heroList[index].count++
            dota2helper.isWin(item.player_slot, item.radiant_win) ? heroList[index].win++ : ''
          } else {
            heroList.push({
              id: item.hero_id,
              count: 1,
              win: dota2helper.isWin(item.player_slot, item.radiant_win) ? 1 : 0
            })
          }
        })

        let maxCountHero = heroList[0].count
        let maxCountHeroId = heroList[0].id

        let minCountHero = heroList[0].count
        let minCountHeroId = heroList[0].id

        let highestHero = heroList[0].win / heroList[0].count
        let highestHeroID = heroList[0].id

        let minimunHero = heroList[0].win / heroList[0].count
        let minimunHeroId = heroList[0].id

        heroList.forEach(hero => {
          if (hero.count > maxCountHero) {
            maxCountHero = hero.count
            maxCountHeroId = hero.id
          }
          if (hero.count < minCountHero) {
            minCountHero = hero.count
            minCountHeroId = hero.id
          }
          if ((hero.win / hero.count) > highestHero) {
            highestHero = (hero.win / hero.count)
            highestHeroID = hero.id
          }
          if ((hero.win / hero.count) < minimunHero) {
            minimunHero = (hero.win / hero.count)
            minimunHeroId = hero.id
          }
        })

        let message = `\n亲爱的【${userInfo.profile.personaname}】${tierLevel}

2021年你总共进行了${total}场比赛,占用了你人生中的${formatDateTime(totalDuration)}钟

其中天梯【${ladderTotal}】场，胜率【${toPercent((ladderSingleWin + ladderPartyWin) / ladderTotal)}】

天梯单排【${ladderSingleTotal}】场，胜率【${toPercent(ladderSingleWin / ladderSingleTotal)}】

天梯组排【${ladderPartyTotal}】场，胜率【${toPercent(ladderPartyWin / ladderPartyTotal)}】

${(ladderPartyWin / ladderPartyTotal) >= (ladderSingleWin / ladderSingleTotal) ? '你更适合开黑上分' : '你更适合单排上分'}

你的年度天梯分【${ladderToday > 0 ? '+' + ladderToday : ladderToday}】

2021年你总共杀敌【${totalKills}】,死亡了【${totalDeaths}】次，获得的【${totalAssists}】次助攻

你的最高击杀记录【${highestKills}】 英雄【${highestKillsHero}】

你的最高死亡记录【${highestDeaths}】 英雄【${highestDeathsHero}】

你的最高助攻纪录【${highestAssists}】 英雄【${highestAssistsHero}】

2021年你总共使用了【${heroList.length}】名英雄

你最爱使用英雄【${getHeroCnName(maxCountHeroId)}】,一共使用了【${maxCountHero}】次

你很少使用英雄【${getHeroCnName(minCountHeroId)}】,一共使用了【${minCountHero}】次

你胜率最高的英雄是【${getHeroCnName(highestHeroID)}】,胜率【${toPercent(highestHero)}】

你胜率最低的英雄是【${getHeroCnName(minimunHeroId)}】,胜率【${toPercent(minimunHero)}】
`
        resolve(message)
      }
    }).catch(e => {
      reject(e)
    })
  })
}

// 监控战绩
function getMonitorRecord(userId) {
  return new Promise((resolve, reject) => {
    getRecordByUserId(userId, 1).then(async res => {
      if (res.length === 0) {
        resolve('')
      } else {
        const timeNow = new Date().getTime()
        const recentMatch = res[0]
        let recentMatchTime = (recentMatch.start_time + recentMatch.duration) * 1000
        let time = timeNow - recentMatchTime
        if (time < 36000000000) {
          console.log(`${userId}检测到${formatTime(time)}内有比赛`)
          const gameRes = await hasMonitorGame({ userId, matchId: recentMatch.match_id })
          if (!gameRes.data) {
            console.log(`${userId}检测到有新比赛`)
            match_id = recentMatch.match_id
            const res = await getReport(match_id, userId)
            resolve({ msg: res, match_id })
          } {
            resolve('')
          }
        } else {
          resolve('')
        }
        // for (let index = 0; index < res.length; index++) {
        //   let recentMatchTime = (res[index].start_time + res[index].duration) * 1000
        //   let time =  timeNow - recentMatchTime
        //   // console.log(`${userId}最近一场比赛${formatTime(time)}`)
        //   if (time < 360000000) {
        //     console.log(`${userId}检测到${formatTime(time)}内有比赛`)
        //     const gameRes = await hasMonitorGame({ userId, matchId: res[index].match_id })
        //     if (!gameRes.data) {
        //       console.log(`${userId}检测到有新比赛`)
        //       // const userInfo = await getUserInfoByUserId(userId)
        //       // const tierLevel = await dota2helper.getRankTier(userInfo.rank_tier, userInfo.leaderboard_rank)
        //       // const hero = await dota2helper.getHeroName(res[index].hero_id)
        //       // match_id = res[index].match_id
        //       // if (dota2helper.isWin(res[index].player_slot, res[index].radiant_win)) {// 赢了
        //       //   if (res[index].party_size === 1) {//单排
        //       //     if (res[index].kills >= 15) { // 宰猪
        //       //       if (res[index].deaths === 0) { // 一次没死
        //       //         msg += `\n单排随便打【${userInfo.profile.personaname}】${tierLevel}又在宰猪,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,一次也没有死,就像个战神一样!!`
        //       //       } else {
        //       //         msg += `\n单排随便打【${userInfo.profile.personaname}】${tierLevel}又在宰猪,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是浪死了【${res[index].deaths}】次`
        //       //       }

        //       //     } else if (res[index].kills < 5) {
        //       //       if (res[index].deaths > 10) {
        //       //         msg += `\n排到四个大腿,就算【${userInfo.profile.personaname}】${tierLevel}超鬼了也能躺赢,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】死了【${res[index].assists}】次`
        //       //       } else {
        //       //         msg += `\n排到四个大腿,【${userInfo.profile.personaname}】${tierLevel}又躺赢了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是死了【${res[index].deaths}】次`
        //       //       }
        //       //     } else {
        //       //       msg += `\n【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中使用【${hero}】赢得了比赛,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //     }
        //       //   } else {
        //       //     if (res[index].kills >= 15) { // 宰猪
        //       //       if (res[index].deaths === 0) { // 一次没死
        //       //         msg += `\n【${userInfo.profile.personaname}】${tierLevel}又在宰猪,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,一次也没有死,就像个战神一样!!`
        //       //       } else {
        //       //         msg = `\n【${userInfo.profile.personaname}】${tierLevel}又在宰猪,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是浪死了【${res[index].deaths}】次`
        //       //       }

        //       //     } else if (res[index].kills < 5) {
        //       //       if (res[index].deaths > 10) {
        //       //         msg += `\n妈的这都没演输!【${userInfo.profile.personaname}】${tierLevel}又超鬼了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】死了【${res[index].assists}】次,奈何队友太牛逼,带ta躺赢了`
        //       //       } else {
        //       //         msg += `\n就随便混一下,【${userInfo.profile.personaname}】${tierLevel}又躺赢了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是死了【${res[index].deaths}】次`
        //       //       }
        //       //     } else {
        //       //       msg += `【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中使用【${hero}】赢得了比赛,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //     }
        //       //   }
        //       // } else {// 输了
        //       //   if (res[index].party_size === 1) { // 单排
        //       //     if (res[index].kills >= 15) { // 杀的多
        //       //       msg += `\n都怪系统匹配的队友不给力!【${userInfo.profile.personaname}】${tierLevel}又输了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是死了【${res[index].deaths}】次`
        //       //     } else if (res[index].kills <= 5) { // 杀的少
        //       //       if (res[index].deaths >= 10) { // 死的多
        //       //         msg += `\n【${userInfo.profile.personaname}】${tierLevel}又输了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】超鬼了!ta送了【${res[index].deaths}】个人头,队友再厉害也顶不住4V6`
        //       //       } else { // 死的少
        //       //         msg += `\n【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中使用【${hero}】梦游一整场,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //       }
        //       //     } else {
        //       //       msg += `\n【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中使用【${hero}】被对面锤爆了,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //     }
        //       //   } else { // 组排
        //       //     if (res[index].kills >= 15) { // 杀的多
        //       //       msg += `\n都怪队友不给力!【${userInfo.profile.personaname}】${tierLevel}又输了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】${dota2helper.getGameMode(res[index].game_mode)}${dota2helper.getLobbyType(res[index].lobby_type)}中TA使用【${hero}】拿下了【${res[index].kills}】个人头【${res[index].assists}】个助攻,但是死了【${res[index].deaths}】次`
        //       //     } else if (res[index].kills <= 5) { // 杀的少
        //       //       if (res[index].deaths >= 10) { // 死的多
        //       //         msg += `\n单排能虐泉,组排就明演!【${userInfo.profile.personaname}】${tierLevel}又输了,在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】【${dota2helper.getGameMode(res[index].game_mode)}】【${dota2helper.getLobbyType(res[index].lobby_type)}】比赛中TA使用【${hero}】超鬼了!ta送了【${res[index].deaths}】个人头`
        //       //       } else { // 死的少
        //       //         msg += `\n组排就硬混!【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}使用【${hero}】梦游一整场,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //       }
        //       //     } else {
        //       //       msg += `\n单排上的分,组排还回去!【${userInfo.profile.personaname}】${tierLevel}在${formatTime(time)}结束的【${dota2helper.getPartSize(res[index].party_size)}】${dota2helper.getGameMode(res[index].game_mode)}${dota2helper.getLobbyType(res[index].lobby_type)}比赛中使用【${hero}】被对面锤爆了,数据:【${res[index].kills}】杀【${res[index].deaths}】死【${res[index].assists}】助攻`
        //       //     }
        //       //   }
        //       // }
        //     }
        //   }
        // }
        // resolve({ msg, match_id })
      }
    }).catch(e => {
      reject(e)
    })
  })
}

// 获取好友
function getPeer(userId) {
  return new Promise((resolve, reject) => {
    getPeerByUserId(userId).then(async res => {
      if (res.length > 0) {
        const userInfo = await getUserInfoByUserId(userId)
        const peerList = []
        res.forEach(item => {
          if (item.with_games) {
            peerList.push({
              account_id: item.account_id,
              games: item.with_games,
              personaname: item.personaname,
              win_probability: item.with_win / item.with_games,
              gpm: item.with_gpm_sum / item.with_games,
              xpm: item.with_xpm_sum / item.with_games,
              score: (item.with_win * 2) - item.with_games
            })
          }
        })
        const highestGamesList = getHighestGamesCount(peerList)
        const highestWinPerList = getHighestWinPer(peerList)
        const minimunGamesList = getMinimumGamesCount(peerList)
        const minimunWinPerList = getMinimumWinPer(peerList)
        const highestScoreList = getHighestScore(peerList)
        const minimunScoreList = getMinimumScore(peerList)
        let msg = `\n亲爱的【${userInfo.profile.personaname}】:

      和你打的最多的是【${highestGamesList[0].personaname}】,你们一起打了【${highestGamesList[0].games}】把,胜率【${toPercent(highestGamesList[0].win_probability)}】,场均gpm【${highestGamesList[0].gpm.toFixed(0)}】,场均xpm【${highestGamesList[0].xpm.toFixed(0)}】。
      
      和你打的最少的是【${minimunGamesList[0].personaname}】,你们一起打了【${minimunGamesList[0].games}】把,胜率【${toPercent(minimunGamesList[0].win_probability)}】,场均gpm【${minimunGamesList[0].gpm.toFixed(0)}】,场均xpm【${minimunGamesList[0].xpm.toFixed(0)}】。
      
      和你胜率最高的是【${highestWinPerList[0].personaname}】,你们一起打了【${highestWinPerList[0].games}】把,胜率【${toPercent(highestWinPerList[0].win_probability)}】,场均gpm【${highestWinPerList[0].gpm.toFixed(0)}】,场均xpm【${highestWinPerList[0].xpm.toFixed(0)}】。
      
      和你胜率最低的是【${minimunWinPerList[0].personaname}】,你们一起打了【${minimunWinPerList[0].games}】把,胜率【${toPercent(minimunWinPerList[0].win_probability)}】,场均gpm【${minimunWinPerList[0].gpm.toFixed(0)}】,场均xpm【${minimunWinPerList[0].xpm.toFixed(0)}】。 
      
      ------------

      【中国好队友】
      ①【${highestScoreList[0].personaname}】胜率【${toPercent(highestScoreList[0].win_probability)}】净胜【${highestScoreList[0].score}】
      ②【${highestScoreList[1].personaname}】胜率【${toPercent(highestScoreList[1].win_probability)}】净胜【${highestScoreList[1].score}】
      ③【${highestScoreList[2].personaname}】胜率【${toPercent(highestScoreList[2].win_probability)}】净胜【${highestScoreList[2].score}】
      ④【${highestScoreList[3].personaname}】胜率【${toPercent(highestScoreList[3].win_probability)}】净胜【${highestScoreList[3].score}】
      ⑤【${highestScoreList[4].personaname}】胜率【${toPercent(highestScoreList[4].win_probability)}】净胜【${highestScoreList[4].score}】

      ------------

      【可能是内鬼】
      ①【${minimunScoreList[0].personaname}】胜率【${toPercent(minimunScoreList[0].win_probability)}】净胜【${minimunScoreList[0].score}】
      ②【${minimunScoreList[1].personaname}】胜率【${toPercent(minimunScoreList[1].win_probability)}】净胜【${minimunScoreList[1].score}】
      ③【${minimunScoreList[2].personaname}】胜率【${toPercent(minimunScoreList[2].win_probability)}】净胜【${minimunScoreList[2].score}】
      ④【${minimunScoreList[3].personaname}】胜率【${toPercent(minimunScoreList[3].win_probability)}】净胜【${minimunScoreList[3].score}】
      ⑤【${minimunScoreList[4].personaname}】胜率【${toPercent(minimunScoreList[4].win_probability)}】净胜【${minimunScoreList[4].score}】
      `
        resolve(msg)
      } else {
        resolve('')
      }
    }).catch(e => {
      reject(e)
    })
  })
}

// 获取统计
function getTotal(userId) {
  return new Promise(async (resolve, reject) => {
    try {
      const userInfo = await getUserInfoByUserId(userId)
      if (userInfo) {
        const killsList = await getTotalByUserId(userId, 'kills') // 击杀
        const deathsList = await getTotalByUserId(userId, 'deaths') // 死亡
        const pingsList = await getTotalByUserId(userId, 'pings') // 发信号
        const neutralKillsList = await getTotalByUserId(userId, 'neutral_kills') // 野怪
        const purchaseTpscrollList = await getTotalByUserId(userId, 'purchase_tpscroll') // 购买tp
        const towerDamageList = await getTotalByUserId(userId, 'tower_damage') // 塔伤
        const heroHealingList = await getTotalByUserId(userId, 'hero_healing') // 治疗
        const heroDamageList = await getTotalByUserId(userId, 'hero_damage') // 伤害
        const goldPerMinList = await getTotalByUserId(userId, 'gold_per_min') // 金钱
        const durationList = await getTotalByUserId(userId, 'duration') // 时长
        const stunsList = await getTotalByUserId(userId, 'stuns') // 控制时间
        const message = `\n亲爱的【${userInfo.profile.personaname}】:

        【${formatDate(killsList[0].start_time)} ${formatLocalTime(killsList[0].start_time)}】你使用【${dota2helper.getHeroCnName(killsList[0].hero_id)}】拿下了【${killsList[0].kills}】杀,直接进行一个猪的宰

        【${formatDate(deathsList[0].start_time)} ${formatLocalTime(deathsList[0].start_time)}】你似乎状态不太好，使用【${dota2helper.getHeroCnName(deathsList[0].hero_id)}】送了【${deathsList[0].deaths}】个人头,4个队友都拦不住

        【${formatDate(pingsList[0].start_time)} ${formatLocalTime(pingsList[0].start_time)}】你好像深得赛老师真传，使用【${dota2helper.getHeroCnName(pingsList[0].hero_id)}】给队友发了【${pingsList[0].pings}】个信号,手应该有点酸吧

        【${formatDate(neutralKillsList[0].start_time)} ${formatLocalTime(neutralKillsList[0].start_time)}】你爱上了野味，使用【${dota2helper.getHeroCnName(neutralKillsList[0].hero_id)}】杀害了【${neutralKillsList[0].neutral_kills}】个野怪,回到野区就跟回家一样
        
        【${formatDate(purchaseTpscrollList[0].start_time)} ${formatLocalTime(purchaseTpscrollList[0].start_time)}】你三路支付，使用【${dota2helper.getHeroCnName(purchaseTpscrollList[0].hero_id)}】购买了【${purchaseTpscrollList[0].purchase_tpscroll}】张tp

        【${formatDate(towerDamageList[0].start_time)} ${formatLocalTime(towerDamageList[0].start_time)}】你化身敌塔师，使用【${dota2helper.getHeroCnName(towerDamageList[0].hero_id)}】对防御塔造成了【${towerDamageList[0].tower_damage}】点伤害

        【${formatDate(heroHealingList[0].start_time)} ${formatLocalTime(heroHealingList[0].start_time)}】你就是战场医生，使用【${dota2helper.getHeroCnName(heroHealingList[0].hero_id)}】为队友治疗了【${heroHealingList[0].hero_healing}】点

        【${formatDate(heroDamageList[0].start_time)} ${formatLocalTime(heroDamageList[0].start_time)}】你简直就是战神，使用【${dota2helper.getHeroCnName(heroDamageList[0].hero_id)}】对敌方英雄总共造成了【${heroDamageList[0].hero_damage}】点伤害

        【${formatDate(goldPerMinList[0].start_time)} ${formatLocalTime(goldPerMinList[0].start_time)}】你化身印钞机，使用【${dota2helper.getHeroCnName(goldPerMinList[0].hero_id)}】每分钟刷了【${goldPerMinList[0].gold_per_min}】块!

        【${formatDate(stunsList[0].start_time)} ${formatLocalTime(stunsList[0].start_time)}】你快把敌方恶心坏了，使用【${dota2helper.getHeroCnName(stunsList[0].hero_id)}】控制敌方英雄总共【${stunsList[0].stuns}】秒

        【${formatDate(durationList[0].start_time)} ${formatLocalTime(durationList[0].start_time)}】你的膀胱受罪了，使用【${dota2helper.getHeroCnName(durationList[0].hero_id)}】进行了一局长达【${formatDuration(durationList[0].duration)}】的世纪大战
        `
        resolve(message)
      } else {
        resolve('请输入正确的id')
      }
    } catch (error) {
      reject(error)
    }
  })
}

// 获取英雄统计
function getHeroTotal(userId) {
  return new Promise(async (resolve, reject) => {
    try {
      const heroesList = await getHeroesByUserId(userId)
      const heroRankList = await getRanksByUserId(userId)
      const userInfo = await getUserInfoByUserId(userId)
      if (heroesList.length > 0 && heroRankList.length > 0 && userInfo) {
        const message = `\n亲爱的【${userInfo.profile.personaname}】:

你最爱使用【${dota2helper.getHeroCnName(heroesList[0].hero_id)}】,陪你度过了【${heroesList[0].games}】把游戏

你很少玩【${dota2helper.getHeroCnName(heroesList[heroesList.length - 1].hero_id)}】,英雄池练一下啊

你的绝中绝是【${dota2helper.getHeroCnName(heroRankList[0].hero_id)}】,选到他就autowin

再多练练【${dota2helper.getHeroCnName(heroRankList[heroRankList.length - 1].hero_id)}】吧,这是你玩的最菜的英雄
        
------------

【钟爱英雄】
①【${dota2helper.getHeroCnName(heroesList[0].hero_id)}】  总共玩了【${heroesList[0].games}】把  胜率【${toPercent(heroesList[0].win / heroesList[0].games)}】
②【${dota2helper.getHeroCnName(heroesList[1].hero_id)}】  总共玩了【${heroesList[1].games}】把  胜率【${toPercent(heroesList[1].win / heroesList[1].games)}】
③【${dota2helper.getHeroCnName(heroesList[2].hero_id)}】  总共玩了【${heroesList[2].games}】把  胜率【${toPercent(heroesList[2].win / heroesList[2].games)}】
        
------------

【勇于尝试】
①【${dota2helper.getHeroCnName(heroesList[heroesList.length - 1].hero_id)}】 总共玩了【${heroesList[heroesList.length - 1].games}】把
②【${dota2helper.getHeroCnName(heroesList[heroesList.length - 2].hero_id)}】 总共玩了【${heroesList[heroesList.length - 2].games}】把
③【${dota2helper.getHeroCnName(heroesList[heroesList.length - 3].hero_id)}】 总共玩了【${heroesList[heroesList.length - 3].games}】把

------------

【三板斧英雄】
①【${dota2helper.getHeroCnName(heroRankList[0].hero_id)}】  分数:【${heroRankList[0].score.toFixed(0)}】
②【${dota2helper.getHeroCnName(heroRankList[1].hero_id)}】  分数:【${heroRankList[1].score.toFixed(0)}】
③【${dota2helper.getHeroCnName(heroRankList[2].hero_id)}】  分数:【${heroRankList[2].score.toFixed(0)}】
  
------------

【三巨坑英雄】
①【${dota2helper.getHeroCnName(heroRankList[heroRankList.length - 1].hero_id)}】  分数:【${heroRankList[heroRankList.length - 1].score.toFixed(0)}】
②【${dota2helper.getHeroCnName(heroRankList[heroRankList.length - 2].hero_id)}】  分数:【${heroRankList[heroRankList.length - 2].score.toFixed(0)}】
③【${dota2helper.getHeroCnName(heroRankList[heroRankList.length - 3].hero_id)}】  分数:【${heroRankList[heroRankList.length - 3].score.toFixed(0)}】
        `
        resolve(message)
      } else {
        resolve('')
      }
    } catch (error) {
      reject(error)
    }
  })
}

// 查询词云
function getWordcloud(userId) {
  return new Promise(async (resolve, reject) => {
    try {
      const userInfo = await getUserInfoByUserId(userId)
      if (userInfo) {
        const wordcloud = await getWordcloudByUserId(userId)
        const myWordCounts = wordcloud['my_word_counts']
        if (Object.keys(myWordCounts).length > 0) {
          const wordcloudList = []
          for (let [key, value] of Object.entries(myWordCounts)) {
            wordcloudList.push({
              word: key,
              count: value
            })
          }
          wordcloudList.sort((a, b) => {
            return b.count - a.count
          })
          const maxLength = wordcloudList.length > 20 ? 20 : wordcloudList.length
          const showWordcloudList = wordcloudList.slice(0, maxLength)

          const _wordList = []

          showWordcloudList.forEach(item => {
            _wordList.push(`【${item.word}】`)
          })

          let wordString = _wordList.join('、')

          let message = `亲爱的【${userInfo.profile.personaname}】:\n你的词云为\n${wordString}`
          resolve(message)
        } else {
          let message = `亲爱的【${userInfo.profile.personaname}】:\n你好像不是很爱打字`
          resolve(message)
        }

      } else {
        resolve('请输入正确的ID')
      }
    } catch (error) {
      reject(error)
    }
  })
}

// 查询历史
function getHistory(userId) {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getPlayerHistory(userId)

      let rankStr = ''
      if (res.ranks && res.ranks.length > 0) {
        let rankObjec = {}
        res.ranks.forEach(item => {
          if (Object.keys(rankObjec)) {
            if (Object.keys(rankObjec).includes('' + item.seasonRankId)) {
              rankObjec[item.seasonRankId].push(item)
            } else {
              rankObjec[item.seasonRankId] = [item]
            }
          } else {
            rankObjec[item.seasonRankId] = [item]
          }
        })

        for (const [key, value] of Object.entries(rankObjec)) {
          const maxRank = getMaxRank(value)
          const minRank = getMinRank(value)
          const finalyRank = getFinalyRank(value)
          rankStr += `第${key}赛季\n最高段位${await dota2helper.getRankTier(maxRank)}\n最低段位${await dota2helper.getRankTier(minRank)}\n最终段位${await dota2helper.getRankTier(finalyRank)}\n`
        }
      } else {
        rankStr = '无'
      }

      let nameStr = ''
      if (res.names && res.names.length > 0) {
        res.names.forEach(name => {
          nameStr += `[${formatDate(name.lastSeenDateTime)}]${name.name}\n`
        })
      } else {
        nameStr = '无'
      }

      const message = `\n【${res.steamAccount.name}】
====比赛总数====
${res.matchCount || "0"}场(${res.winCount || "0"}胜/${(res.matchCount - res.winCount) || "0"}负 ${toPercent(res.winCount / res.matchCount)}胜率)
====行为分====
${res.behaviorScore || '0'}分
====首次比赛====
${formatDate(res.firstMatchDate)} 
====段位=====
${rankStr}
====昵称====
${nameStr}
`
      resolve(message)

    } catch (error) {
      console.log(error)
      reject(error)
    }
  })
}

// 根据id列表获取name列表
function getNameListByUserIdList(userIdList) {
  return new Promise(async (resolve, reject) => {
    try {
      const monitorList = []
      for (let index = 0; index < userIdList.length; index++) {
        const userInfo = await getUserInfoByUserId(userIdList[index])
        if (userInfo.profile) {
          const userName = userInfo.profile.personaname
          monitorList.push(`${userName}[${userIdList[index]}]`)
        }
      }
      resolve(monitorList)
    } catch (error) {
      reject(error)
    }
  })
}

function isOpenUser(userId) {
  return new Promise((resolve, reject) => {
    getUserInfoByUserId(userId).then(res => {
      if (res) {
        resolve(true)
      } else {
        resolve(false)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

function getMaxRank(rankList) {
  if (rankList.length > 0) {
    if (rankList.length === 1) {
      return rankList[0].rank
    } else {
      let max = rankList[0].rank
      rankList.forEach(item => {
        if (item.rank > max) {
          max = item.rank
        }
      })
      return max
    }
  } else {
    return 0
  }
}

function getMinRank(rankList) {
  if (rankList.length > 0) {
    if (rankList.length === 1) {
      return rankList[0].rank
    } else {
      let min = rankList[0].rank
      rankList.forEach(item => {
        if (item.rank < min) {
          min = item.rank
        }
      })
      return min
    }
  } else {
    return 0
  }
}

function getFinalyRank(rankList) {
  if (rankList.length > 0) {
    rankList.sort((a, b) => { return new Date(b.asOfDateTime) - new Date(a.asOfDateTime) })
    return rankList[0].rank
  } else {
    return 0
  }
}

function formatTime(time) {
  const minutes = Math.floor(time / (60 * 1000))
  return `${minutes}分钟前`
}

function formatDate(time) {
  return new Date(time * 1000).toLocaleDateString()
}

function formatLocalTime(time) {
  return new Date(time * 1000).toLocaleTimeString()
}

function formatDuration(time) {
  return `${(time / 60).toFixed(0)}:${time % 60}`
}

function toPercent(point) {
  return Number.isNaN(point) ? '0%' : `${Number(point * 100).toFixed(1)}%`
}

function getHighestGamesCount(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return b.games - a.games })
}

function getHighestWinPer(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return b.win_probability - a.win_probability })
}

function getMinimumGamesCount(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return a.games - b.games })
}

function getMinimumWinPer(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return a.win_probability - b.win_probability })
}

function getHighestScore(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return b.score - a.score })
}

function getMinimumScore(peerList) {
  const _peerList = deepClone(peerList)
  return _peerList.sort((a, b) => { return a.score - b.score })
}

function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone(obj[key]);
        } else {
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
}

function getToday() {
  return new Promise((resolve, reject) => {
    try {
      let todayDate = new Date()
      let month = (todayDate.getMonth() + 1) < 10 ? '0' + (todayDate.getMonth() + 1) : (todayDate.getMonth() + 1 + '')
      let day = todayDate.getDate() < 10 ? '0' + todayDate.getDate() : '' + todayDate.getDate()
      resolve(month + day)
    } catch (error) {
      reject(error)
    }
  })
}

function formatDateTime(duration) {
  let secondTime = parseInt(duration);// 秒
  let minuteTime = 0;// 分
  let hourTime = 0;// 时
  if (secondTime > 60) {
    minuteTime = parseInt(secondTime / 60);
    secondTime = parseInt(secondTime % 60);
    if (minuteTime > 60) {
      hourTime = parseInt(minuteTime / 60);
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  let result = "" + parseInt(secondTime) + "秒";
  if (minuteTime > 0) {
    result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + "小时" + result;
  }
  return result;
}

module.exports = {
  getRecord,
  getMonitorRecord,
  getPeer,
  getTotal,
  getHeroTotal,
  getWordcloud,
  getHistory,
  getNameListByUserIdList,
  isOpenUser,
  getToday,
  getLastWeekRecord,
  getThisYearRecord
}